package sk.tramtatiri.pages.users;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import sk.tramtatiri.MySession;
import sk.tramtatiri.data.dao.interfaces.FoodDao;
import sk.tramtatiri.data.dao.interfaces.InOutHelperDao;
import sk.tramtatiri.data.dao.interfaces.RecipeDao;
import sk.tramtatiri.data.dao.interfaces.UserDao;
import sk.tramtatiri.data.dao.interfaces.UserFoodDao;
import sk.tramtatiri.data.dao.interfaces.UserRecipeDao;
import sk.tramtatiri.data.dataobjects.Food;
import sk.tramtatiri.data.dataobjects.InOutHelper;
import sk.tramtatiri.data.dataobjects.Recipe;
import sk.tramtatiri.data.dataobjects.UserFood;

public class FoodDetailPage extends UserPageTemplate{

	@SpringBean
	private FoodDao foodDao;
	@SpringBean
	private UserFoodDao userFoodDao;
	@SpringBean
	private UserRecipeDao userRecipeDao;
	@SpringBean
	private UserDao userDao;
	private Food food;
	@SpringBean
	private RecipeDao recipeDao;
	
	@SpringBean
	private InOutHelperDao inOutHelperDao;
	
	public FoodDetailPage(PageParameters pageParameters) {
		String name = null;
		if(!pageParameters.isEmpty()){
			name = (String) pageParameters.get("name");
		}
		food = foodDao.findName(name);
		
		FeedbackPanel feedback = new FeedbackPanel("feedback");
		feedback.setOutputMarkupId(true);
		add(feedback);
		
		final Form<?> form = new Form<Void>("formFood");
		form.add(new Label("foodName", Model.of(food.getName())));
		
		form.add(new Label("foodDescription", Model.of(food.getDescription())).setOutputMarkupId(true));
		form.add(new Label("foodCalories", Model.of(food.getCalories())).setOutputMarkupId(true));
		form.add(new Label("foodFats", Model.of(food.getFats())).setOutputMarkupId(true));
		form.add(new Label("foodProteins", Model.of(food.getProteins())).setOutputMarkupId(true));
		form.add(new Label("foodSaccharides", Model.of(food.getSaccharides())).setOutputMarkupId(true));
		TextField textField = new TextField("foodWeight", Model.of(100));
		textField.setOutputMarkupId(true);
		textField.add(new AjaxFormComponentUpdatingBehavior("onKeyUp") {
			private static final long serialVersionUID = -6012179013011456929L;

			@Override
			protected void onUpdate(AjaxRequestTarget target) {
				String weight = form.get("foodWeight").getDefaultModelObjectAsString();
				if(weight.matches("\\d+")){
					target.addComponent(form.get("foodCalories").setDefaultModelObject(Math.round(Float.valueOf(weight)*food.getCalories()/100)));
					target.addComponent(form.get("foodFats").setDefaultModelObject(Math.round(Float.valueOf(weight)*food.getFats()/100)));
					target.addComponent(form.get("foodProteins").setDefaultModelObject(Math.round(Float.valueOf(weight)*food.getProteins()/100)));
					target.addComponent(form.get("foodSaccharides").setDefaultModelObject(Math.round(Float.valueOf(weight)*food.getSaccharides()/100)));
				}
			}
		});
		form.add(textField);
		
		List<Recipe> allRecipes = recipeDao.orderBy("name");
		List<String> recipes = new ArrayList<String>();
		for (Recipe recipe : allRecipes) {
			String[] ingredients = recipe.getIngredients();
			for(int i = 0; i < ingredients.length; i++){
				if(ingredients[i].equalsIgnoreCase(food.getName())){
					recipes.add(recipe.getName());
				}
			}
		}
		
		form.add(new ListView<String>("row", recipes) {
			private static final long serialVersionUID = -2228328141564874571L;

			@Override
			protected void populateItem(ListItem<String> item) {
				String recipeName = item.getModelObject();
					
				PageParameters parameters = new PageParameters();
				parameters.put("name", recipeName);
				BookmarkablePageLink bpl = new BookmarkablePageLink("linkToRecipe", RecipeDetailPage.class, parameters);
				bpl.add(new Label("recipeName", Model.of(recipeName)));
				item.add(bpl);
			}
		});
		
		

		Button button = new Button("submitBtn"){
			private static final long serialVersionUID = 678614432694793988L;

			public void onSubmit() {
				UserFood userFood = new UserFood();
				
				Calendar cal = Calendar.getInstance();
				cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
						cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
				
				userFood.setDate(new Date(cal.getTimeInMillis()));
				userFood.setUser(userDao.load(((MySession) getSession())
						.getUserID()));
				userFood.setUserId(((MySession) getSession())
						.getUserID());
				//TODO WTF
				userFood.setQuantity(Integer.valueOf(form.get("foodWeight").getDefaultModelObjectAsString()));
				userFood.setTotalCalories(Integer.valueOf(form.get("foodCalories").getDefaultModelObjectAsString()));
				userFood.setFood(food);
				long idFood = food.getId();
				userFood.setFoodId(idFood);
				userFoodDao.save(userFood);
				
				int totalTodayRec = userRecipeDao.sumUserToday(((MySession)getSession()).getUserID());
				int totalTodayFood = userFoodDao.sumUserToday(((MySession)getSession()).getUserID());
				InOutHelper todayHelper = inOutHelperDao.findByUserToday(((MySession)getSession()).getUserID());
				if(todayHelper!=null)
					todayHelper.setCaloriesIn(totalTodayFood+totalTodayRec);
				else {
					InOutHelper newHelper = new InOutHelper();
					newHelper.setDate(new Date(cal.getTimeInMillis()));
					newHelper.setCaloriesIn(totalTodayFood+totalTodayRec);
					newHelper.setUsrid(((MySession)getSession()).getUserID());
					inOutHelperDao.save(newHelper);
				}
				info("Potravina bola pridana k zjedenym");
				
				userDao.load(((MySession) getSession()).getUserID())
						.getFoods().add(userFood);
				food.getUsers().add(userFood);
			};
		};
		
		if (((MySession)getSession()).hasPermission()) {
			button.setVisible(true);
		} else {
			button.setVisible(false);
		}
		
		form.add(button);
		
		add(form);
	}
	
	@Override
	public String getPageTitle() {
		if(food != null){
			return "chudnite-zdravo.com - " + food.getName();
		}
		return "chudnite-zdravo.com";
	}

}
